package com.woniuxy.ServletContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @auther linke
 * @create 2021-10-19 14:35
 */
@WebServlet("/servletContextDemo05")
public class ServletContextDemo05 extends HttpServlet {
    /**
     * 获取真实路径
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("servletContextDemo05...执行了");

       /* //获取真实路径
        String realPath = req.getServletContext().getRealPath("");
        System.out.println(realPath);//E:\tomcat\apache-tomcat-8.5.31\webapps\web03\*/

        //读取文件
       /* String realPath1 = req.getServletContext().getRealPath("aaa.properties");//value5
        String realPath2 = req.getServletContext().getRealPath("/WEB-INF/aaa.properties");//value4
        String realPath3 = req.getServletContext().getRealPath("/static/img/aaa.properties");//value3
       String realPath4 = req.getServletContext().getRealPath("/WEB-INF/classes/aaa.properties");//value2
        String realPath5 = req.getServletContext().getRealPath("/WEB-INF/classes/com/ServletContext/aaa.properties");//没有

        */

        Properties p;

        try {
            p = new Properties();
//            p.load(ServletContextDemo05.class.getClassLoader().getResourceAsStream("/aaa.properties"));
//            p.load(ServletContextDemo05.class.getClassLoader().getResourceAsStream("/aaa.properties"));
           // p.load(ServletContextDemo05.class.getClassLoader().getResourceAsStream("../../../../aaa.properties"));//value3
            p.load(ServletContextDemo05.class.getClassLoader().getResourceAsStream("aaa.properties"));
            String value = p.getProperty("key");
            System.out.println(value);//value2
        }catch (Exception e){
            e.printStackTrace();
        }



    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
